﻿package net.wangit.view.element.component;

import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.support.AbstractElementWriter;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitConfigurationException;
import net.wangit.view.unit.util.UnitUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class UnitElementWriter extends AbstractElementWriter {

	private static Log log = LogFactory
			.getLog(net.wangit.view.element.component.UnitElementWriter.class);

	public UnitElementWriter() {
	}

	protected void writeText(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControl(ac, html, ec, row);
	}

	protected void writeTextWithValue(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControl(ac, html, ec, row);
	}

	protected void writeControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		UnitComponent uc = (UnitComponent) ec.getObject();
		if (uc != null)
			writeControl(ac, html, uc);
	}

	protected void writeReadOnlyControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeControl(ac, html, ec, row);
	}

	protected void writeDisabledControl(ActionContext actioncontext,
			StringBuffer stringbuffer, ElementComponent elementcomponent,
			Row row1) {
	}

	protected void writeInvisibleControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		UnitComponent uc = (UnitComponent) ec.getObject();
		if (uc != null) {
			String tableAttribute = uc.getTableAttribute();
			if (tableAttribute == null)
				tableAttribute = "style='display:none'";
			else
				tableAttribute = (new StringBuilder(String
						.valueOf(tableAttribute))).append(
						"style='display:none'").toString();
			uc.setTableAttribute(tableAttribute);
			writeControl(ac, html, uc);
		}
	}

	protected void writeHidden(ActionContext actioncontext,
			StringBuffer stringbuffer, ElementComponent elementcomponent,
			Row row1) {
	}

	private void writeControl(ActionContext ac, StringBuffer html,
			UnitComponent uc) {
		try {
			String unitHtml = uc.write(ac);
			if (unitHtml != null)
				html.append(unitHtml);
		} catch (Exception e) {
			log.error((new StringBuilder("UnitElement error: ")).append(
					UnitUtil.getUrl(uc)).toString());
			throw new UnitConfigurationException("UnitElement error: ", e);
		}
	}

}
